/*
 * TelaPrincipal.java
 *
 * Created on 28 de Março de 2009, 17:30
 */
package iu;

import comp.racer.common.rn.Jogador;
import comp.racer.common.rn.JogadorObserver;
import java.awt.event.KeyEvent;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import rn.Texto;
import so.Cliente;

/**
 *
 * @author  Germano
 */
public class PartidaTela extends TelaPadrao implements JogadorObserver {

    private Texto textoPartida;

    //atributos de interface
    private Map<String, JProgressBar> loginProgressBarMap;
    private Map<String, JLabel> loginCPMMap;

    // constructores
    public PartidaTela(Texto textoPartida) {

        setLoginCPMMap(new HashMap<String, JLabel>());
        setLoginProgressBarMap(new HashMap<String, JProgressBar>());
        setTextoPartida(textoPartida);
        initComponents();
        updateComponents();
        Jogador.attach(this);
        exibeTela();
    }



    // metodos
    private void updateComponents() {

        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        List<Jogador> jogadoresList = new Vector<Jogador>(getLoginJogadorMap().values());
        ArrayList<JLabel> labelsCPM = new ArrayList<JLabel>();
        ArrayList<JLabel> labelsLogin = new ArrayList<JLabel>();
        ArrayList<JProgressBar> barrasDeProgresso = new ArrayList<JProgressBar>();

        Map<String, JProgressBar> loginProgressoMap = getLoginProgressBarMap();
        //Map<String, JLabel> loginCPMMap = getLoginCPMMap();



        barrasDeProgresso.add(pbJogador1);
        barrasDeProgresso.add(pbJogador2);
        barrasDeProgresso.add(pbJogador3);
        barrasDeProgresso.add(pbJogador4);

        labelsCPM.add(lbCPMJogador1);
        labelsCPM.add(lbCPMJogador2);
        labelsCPM.add(lbCPMJogador3);
        labelsCPM.add(lbCPMJogador4);

        labelsLogin.add(lbLoginJogador1);
        labelsLogin.add(lbLoginJogador2);
        labelsLogin.add(lbLoginJogador3);
        labelsLogin.add(lbLoginJogador4);

        for (int i = 0; i < jogadoresList.size(); i++) {

            labelsCPM.get(i).setText(jogadoresList.get(i).getCpm().toString() + " CPM");
            labelsLogin.get(i).setText(jogadoresList.get(i).getLogin());
            barrasDeProgresso.get(i).setValue(jogadoresList.get(i).getProgresso());
            barrasDeProgresso.get(i).setMaximum(getTextoPartida().getNCaracteres());
            loginProgressoMap.put(labelsLogin.get(i).getText(), barrasDeProgresso.get(i));
            loginCPMMap.put(labelsLogin.get(i).getText(), labelsCPM.get(i));

        }

        //Inicialização da área de texto com o texto da partida
        List<String> listaPalavras = getTextoPartida().getListaPalavras();

        String stringPalavras = new String();
        String aux;
        for (int i = 0; i < listaPalavras.size(); i++) {

            if (i == getTextoPartida().getIndicePalavraCorrente()) {
                aux = "<b>" + listaPalavras.get(i) + "</b> ";
            } else {
                aux = listaPalavras.get(i) + " ";
            }


            stringPalavras = stringPalavras.concat(aux);

        }

        getTextoPane().setText(stringPalavras);
        getTextoPane().setContentType("text/html");

        getLbPalabraInvalida().setVisible(false);



    }

    public void update() {


        List<Jogador> listJogador = new Vector<Jogador>(getLoginJogadorMap().values());
        for (Jogador jogador : listJogador) {
            getLoginProgressBarMap().get(jogador.getLogin()).setValue(jogador.getProgresso());
            DecimalFormat format = new DecimalFormat("##,###.##");
            getLoginCPMMap().get(jogador.getLogin()).setText(format.format(jogador.getCpm()) + " CPM");
        }


    }

    private String coletaPalavra() {
        return getTfPalavraAtual().getText().trim();

    }


    private void validaPalavra() {
        String palavra = coletaPalavra();
        if (palavra.equals(getTextoPartida().getPalavraCorrente())) {
            notificaProgressoJogador(palavra.length());
            getLbPalabraInvalida().setVisible(false);
        } else {
            getLbPalabraInvalida().setVisible(true);
        }
    }

    private void atualizaTexto() {
       
        System.out.println("Texto na tela sendo atualizado");
        String textoNovo = getTextoPane().getText();
        String palavraNegrito = getTextoPartida().getPalavraCorrente();
        String palavraAntiga = getTextoPartida().getPalavraAnterior();
        textoNovo = textoNovo.replace("<b>" + palavraAntiga + "</b>", palavraAntiga);
        if (getTextoPartida().getIndicePalavraCorrente()==getTextoPartida().getListaPalavras().size()-1){
            textoNovo = textoNovo.replace(" "+palavraNegrito , " <b>" + palavraNegrito + "</b> ");
        }
        else textoNovo = textoNovo.replace(" "+palavraNegrito+" " , " <b>" + palavraNegrito + "</b> ");
        getTextoPane().setText(textoNovo);
    }

    private void notificaProgressoJogador(int nCaracteres) {
        getCliente().notificaProgressoJogador(nCaracteres);
        getTextoPartida().avancaPalavra();
        atualizaTexto();



    }
    

   

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lbCompRacer = new javax.swing.JLabel();
        progressoPanel = new javax.swing.JPanel();
        pbJogador1 = new javax.swing.JProgressBar();
        pbJogador2 = new javax.swing.JProgressBar();
        pbJogador3 = new javax.swing.JProgressBar();
        pbJogador4 = new javax.swing.JProgressBar();
        lbCPMJogador1 = new javax.swing.JLabel();
        lbCPMJogador2 = new javax.swing.JLabel();
        lbCPMJogador3 = new javax.swing.JLabel();
        lbCPMJogador4 = new javax.swing.JLabel();
        lbLoginJogador1 = new javax.swing.JLabel();
        lbLoginJogador2 = new javax.swing.JLabel();
        lbLoginJogador3 = new javax.swing.JLabel();
        lbLoginJogador4 = new javax.swing.JLabel();
        tfPalavraAtual = new javax.swing.JTextField();
        lbPalavra = new javax.swing.JLabel();
        sairBt = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        textoPane = new javax.swing.JEditorPane();
        lbPalabraInvalida = new javax.swing.JLabel();

        setTitle("CompRacer - Partida");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        lbCompRacer.setText("CompRacer");

        lbCPMJogador1.setText("0 cpm");

        lbCPMJogador2.setText("0 cpm");

        lbCPMJogador3.setText("0 cpm");

        lbCPMJogador4.setText("0 cpm");

        lbLoginJogador1.setText("-");

        lbLoginJogador2.setText("-");

        lbLoginJogador3.setText("-");

        lbLoginJogador4.setText("-");

        javax.swing.GroupLayout progressoPanelLayout = new javax.swing.GroupLayout(progressoPanel);
        progressoPanel.setLayout(progressoPanelLayout);
        progressoPanelLayout.setHorizontalGroup(
            progressoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(progressoPanelLayout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addGroup(progressoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(lbLoginJogador2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lbLoginJogador1, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
                    .addComponent(lbLoginJogador3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lbLoginJogador4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(progressoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(progressoPanelLayout.createSequentialGroup()
                        .addComponent(pbJogador4, javax.swing.GroupLayout.PREFERRED_SIZE, 474, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbCPMJogador4))
                    .addGroup(progressoPanelLayout.createSequentialGroup()
                        .addComponent(pbJogador3, javax.swing.GroupLayout.PREFERRED_SIZE, 474, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbCPMJogador3))
                    .addGroup(progressoPanelLayout.createSequentialGroup()
                        .addComponent(pbJogador2, javax.swing.GroupLayout.PREFERRED_SIZE, 474, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbCPMJogador2))
                    .addGroup(progressoPanelLayout.createSequentialGroup()
                        .addComponent(pbJogador1, javax.swing.GroupLayout.PREFERRED_SIZE, 474, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbCPMJogador1)))
                .addGap(54, 54, 54))
        );
        progressoPanelLayout.setVerticalGroup(
            progressoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(progressoPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(progressoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lbCPMJogador1)
                    .addComponent(pbJogador1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbLoginJogador1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(progressoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lbCPMJogador2)
                    .addComponent(pbJogador2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbLoginJogador2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(progressoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(pbJogador3, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbCPMJogador3)
                    .addComponent(lbLoginJogador3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(progressoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(pbJogador4, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbCPMJogador4)
                    .addComponent(lbLoginJogador4))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        tfPalavraAtual.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfPalavraAtualActionPerformed(evt);
            }
        });
        tfPalavraAtual.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                tfPalavraAtualKeyTyped(evt);
            }
        });

        lbPalavra.setText("Palavra:");

        sairBt.setText("Sair");
        sairBt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sairBtActionPerformed(evt);
            }
        });

        textoPane.setContentType("text/html");
        textoPane.setEditable(false);
        textoPane.setDisabledTextColor(new java.awt.Color(0, 0, 0));
        textoPane.setEnabled(false);
        textoPane.setFocusCycleRoot(false);
        jScrollPane1.setViewportView(textoPane);

        lbPalabraInvalida.setDisplayedMnemonic(' ');
        lbPalabraInvalida.setForeground(new java.awt.Color(255, 0, 51));
        lbPalabraInvalida.setText("Palavra inválida");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(252, 252, 252)
                        .addComponent(lbCompRacer))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(lbPalavra)
                                .addGap(18, 18, 18)
                                .addComponent(tfPalavraAtual, javax.swing.GroupLayout.PREFERRED_SIZE, 459, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                                .addComponent(lbPalabraInvalida, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                            .addComponent(progressoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 654, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(567, 567, 567)
                        .addComponent(sairBt, javax.swing.GroupLayout.DEFAULT_SIZE, 165, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbCompRacer)
                .addGap(4, 4, 4)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(progressoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbPalavra)
                    .addComponent(tfPalavraAtual, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbPalabraInvalida, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addComponent(sairBt)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tfPalavraAtualActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfPalavraAtualActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_tfPalavraAtualActionPerformed

    private void tfPalavraAtualKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfPalavraAtualKeyTyped
        if (evt.getKeyChar() == KeyEvent.VK_SPACE) {
            System.out.println("Usuário pressionou espaço");

            validaPalavra();
            getTfPalavraAtual().setText("");


        }
    }//GEN-LAST:event_tfPalavraAtualKeyTyped

    private void sairBtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sairBtActionPerformed
        finalizaPrograma();
       
    }//GEN-LAST:event_sairBtActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing

        finalizaPrograma();
    }//GEN-LAST:event_formWindowClosing

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbCPMJogador1;
    private javax.swing.JLabel lbCPMJogador2;
    private javax.swing.JLabel lbCPMJogador3;
    private javax.swing.JLabel lbCPMJogador4;
    private javax.swing.JLabel lbCompRacer;
    private javax.swing.JLabel lbLoginJogador1;
    private javax.swing.JLabel lbLoginJogador2;
    private javax.swing.JLabel lbLoginJogador3;
    private javax.swing.JLabel lbLoginJogador4;
    private javax.swing.JLabel lbPalabraInvalida;
    private javax.swing.JLabel lbPalavra;
    private javax.swing.JProgressBar pbJogador1;
    private javax.swing.JProgressBar pbJogador2;
    private javax.swing.JProgressBar pbJogador3;
    private javax.swing.JProgressBar pbJogador4;
    private javax.swing.JPanel progressoPanel;
    private javax.swing.JButton sairBt;
    private javax.swing.JEditorPane textoPane;
    private javax.swing.JTextField tfPalavraAtual;
    // End of variables declaration//GEN-END:variables

    // getters e setters


    private Map<String, Jogador> getLoginJogadorMap() {
        return getCliente().getLoginJogadorMap();
    }

    private Map<String, JProgressBar> getLoginProgressBarMap() {
        return loginProgressBarMap;
    }

    private void setLoginProgressBarMap(Map<String, JProgressBar> lblLoginProgressBarMap) {
        this.loginProgressBarMap = lblLoginProgressBarMap;
    }

    private Map<String, JLabel> getLoginCPMMap() {
        return loginCPMMap;
    }

    public void setLoginCPMMap(Map<String, JLabel> loginCPMMap) {
        this.loginCPMMap = loginCPMMap;
    }

    public JEditorPane getTextoPane() {
        return textoPane;
    }

    public void setTextoPane(JEditorPane textoPane) {
        this.textoPane = textoPane;
    }

    public Texto getTextoPartida() {
        return textoPartida;
    }

    public void setTextoPartida(Texto textoPartida) {
        this.textoPartida = textoPartida;
    }

    public JTextField getTfPalavraAtual() {
        return tfPalavraAtual;
    }

    public void setTfPalavraAtual(JTextField tfPalavraAtual) {
        this.tfPalavraAtual = tfPalavraAtual;
    }

    public JLabel getLbPalabraInvalida() {
        return lbPalabraInvalida;
    }
}
